﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using fideeraSoft.Handlers;
using System.Drawing;
using fideeraSoft.Utils;
using System.Data;
using System.Data.SqlClient;

namespace fideeraSoft.Paneles
{
    class UsuarioPanelModificar : PanelGeneral
    {
        private TableLayoutPanel tlpBuscarUsuarioDNI;
        private DataGridView dgvUsuarios;
        private TableLayoutPanel tlpBuscarUsuarioUsername;
        
        private SqlDataAdapter adapter;
        private DataSet ds;
        private DataSet changes;
        private Button btBuscarUsuarioUsername;
        private Button btBuscarUsuarioDNI;
        private TextBox tbBuscarUsuarioDNI;
        private TextBox tbBuscarUsuarioUsername;
        private Button btGuardarCambios;
        
        private int locationTlpBuscarUsuarioDNI;
        private int locationBtCambios = 0;
        private int locationTlpBuscarUsuarioUsername= 0;
        private SqlCommandBuilder cmdBuilder;
        
        public UsuarioPanelModificar(Handler handler)
        {
            this.formatearPanelGeneral(handler);
            try
            {
                InitializeComponent();                

                this.formatearTableTitulo("MODIFICACIÓN DE USUARIO");


                string query = "SELECT ID AS [ID Usuario], nombre AS Nombre, apellido AS Apellido, dni AS DNI, username AS [Nombre de Usuario], pass AS Contraseña, email AS Email, tel AS Teléfono, cel AS Celular, jerarquia AS Jerarquía FROM Usuario";
                adapter= SQLclass.obtenerAdapter(query);
                if (adapter != null)
                {
                   ds = new DataSet();
                   adapter.Fill(ds);
                                      

                   dgvUsuarios.DataSource = ds.Tables[0];

                   if (ds.Tables[0].Rows.Count <= 0)
                       MessageBox.Show("NO HAY NINGUN USUARIO CARGADO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);


                   formatearDataGrid();

                   tlpBuscarUsuarioUsername.Controls.Add(btBuscarUsuarioUsername);
                   tlpBuscarUsuarioUsername.Controls.Add(tbBuscarUsuarioUsername);

                   formatearTablaBuscarUsuarioUsername();

                   tlpBuscarUsuarioDNI.Controls.Add(btBuscarUsuarioDNI);
                   tlpBuscarUsuarioDNI.Controls.Add(tbBuscarUsuarioDNI);

                   formatearTablaBuscarUsuarioDNI();
                    
                   formatearBotonGuardar();
                    
                    
                    this.Controls.Add(dgvUsuarios);
                    this.Controls.Add(tlpBuscarUsuarioDNI);
                    this.Controls.Add(tlpBuscarUsuarioUsername);
                    this.Controls.Add(btGuardarCambios);
                }              
                else {
                    //CLogger.Append("[ProveedorPanelMostrar] Lista Proveedor mostrar Null: ", CLogger.INFO);      //DEBUG
                    MessageBox.Show("NO HAY NINGUN USUARIO CARGADO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.handler.backToPrincipal();
                }
                
            }
            catch (MiException ex)
            {

                CLogger.Append("[ProveedorPanelMostrar] Exception: " + ex, CLogger.ERROR);      //DEBUG
            
            }      
                    
        }




        #region FORMATEAR FORMATEOS

        private void formatearDataGrid()
        {
            dgvUsuarios.AutoGenerateColumns = true;
            dgvUsuarios.Size = new Size(this.Size.Width - 100, this.Size.Height - 400);
            dgvUsuarios.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.Fill);
            dgvUsuarios.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllHeaders);
            dgvUsuarios.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            dgvUsuarios.BorderStyle = BorderStyle.Fixed3D;
            
            dgvUsuarios.Location = new Point(MetodosGenerales.calcularCenterWidth(this.Size.Width, dgvUsuarios.Size.Width), this.InitialRealPointVertical);
        }

        private void formatearTablaBuscarUsuarioUsername()
        {
            tlpBuscarUsuarioUsername.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
            tlpBuscarUsuarioUsername.BackColor = Color.LightCyan;
            tlpBuscarUsuarioUsername.Size = new Size(400, tbBuscarUsuarioUsername.Size.Height + 9);
            //tlpBuscarProv.Size = new Size(lbBuscarProvCuil.Size.Width + tbBuscarProvCuil.Size.Width + 10,tbBuscarProvCuil.Size.Height);
            int wid = MetodosGenerales.calcularCenterWidth(handler.FormFrame.Size.Width, tlpBuscarUsuarioUsername.Size.Width);

            locationTlpBuscarUsuarioUsername = this.InitialRealPointVertical + dgvUsuarios.Size.Height + 15;

            tlpBuscarUsuarioUsername.Location = new Point(wid, locationTlpBuscarUsuarioUsername);

        }

        private void formatearTablaBuscarUsuarioDNI()
        {
            tlpBuscarUsuarioDNI.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
            tlpBuscarUsuarioDNI.BackColor = Color.LightCyan;
            tlpBuscarUsuarioDNI.Size = new Size(400, tbBuscarUsuarioDNI.Size.Height + 9);
            locationTlpBuscarUsuarioDNI = locationTlpBuscarUsuarioUsername + 40;
            tlpBuscarUsuarioDNI.Location = new Point(MetodosGenerales.calcularCenterWidth(this.Size.Width, tlpBuscarUsuarioDNI.Size.Width), locationTlpBuscarUsuarioDNI);

        }

        private void formatearBotonGuardar()
        {
            locationBtCambios = locationTlpBuscarUsuarioDNI + tlpBuscarUsuarioDNI.Size.Height + 10;
            btGuardarCambios.Location = new Point(MetodosGenerales.calcularCenterWidth(this.Size.Width, btGuardarCambios.Size.Width), locationBtCambios);
        }


        #endregion

        #region INICIALIZAR
        private void InitializeComponent()
        {
            this.tlpBuscarUsuarioDNI = new System.Windows.Forms.TableLayoutPanel();
            this.dgvUsuarios = new System.Windows.Forms.DataGridView();
            this.tlpBuscarUsuarioUsername = new System.Windows.Forms.TableLayoutPanel();
            this.btBuscarUsuarioUsername = new System.Windows.Forms.Button();
            this.btBuscarUsuarioDNI = new System.Windows.Forms.Button();
            this.tbBuscarUsuarioDNI = new System.Windows.Forms.TextBox();
            this.tbBuscarUsuarioUsername = new System.Windows.Forms.TextBox();
            this.btGuardarCambios = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dgvUsuarios)).BeginInit();
            this.SuspendLayout();
            // 
            // tlpBuscarUsuarioDNI
            // 
            this.tlpBuscarUsuarioDNI.ColumnCount = 2;
            this.tlpBuscarUsuarioDNI.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarUsuarioDNI.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarUsuarioDNI.Location = new System.Drawing.Point(0, 0);
            this.tlpBuscarUsuarioDNI.Name = "tlpBuscarUsuarioDNI";
            this.tlpBuscarUsuarioDNI.RowCount = 1;
            this.tlpBuscarUsuarioDNI.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarUsuarioDNI.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarUsuarioDNI.Size = new System.Drawing.Size(400, 50);
            this.tlpBuscarUsuarioDNI.TabIndex = 0;
            // 
            // dgvUsuarios
            // 
            this.dgvUsuarios.AllowUserToResizeRows = false;
            this.dgvUsuarios.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgvUsuarios.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnF2;
            this.dgvUsuarios.Location = new System.Drawing.Point(0, 0);
            this.dgvUsuarios.Name = "dgvUsuarios";
            this.dgvUsuarios.Size = new System.Drawing.Size(240, 150);
            this.dgvUsuarios.TabIndex = 0;
            this.dgvUsuarios.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvUsuarios_CellContentClick);
            // 
            // tlpBuscarUsuarioUsername
            // 
            this.tlpBuscarUsuarioUsername.ColumnCount = 2;
            this.tlpBuscarUsuarioUsername.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarUsuarioUsername.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarUsuarioUsername.Location = new System.Drawing.Point(0, 0);
            this.tlpBuscarUsuarioUsername.Name = "tlpBuscarUsuarioUsername";
            this.tlpBuscarUsuarioUsername.RowCount = 1;
            this.tlpBuscarUsuarioUsername.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarUsuarioUsername.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tlpBuscarUsuarioUsername.Size = new System.Drawing.Size(400, 50);
            this.tlpBuscarUsuarioUsername.TabIndex = 0;
            // 
            // btBuscarUsuarioUsername
            // 
            this.btBuscarUsuarioUsername.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.btBuscarUsuarioUsername.BackColor = System.Drawing.Color.AliceBlue;
            this.btBuscarUsuarioUsername.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btBuscarUsuarioUsername.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btBuscarUsuarioUsername.Location = new System.Drawing.Point(0, 0);
            this.btBuscarUsuarioUsername.Name = "btBuscarUsuarioUsername";
            this.btBuscarUsuarioUsername.Size = new System.Drawing.Size(75, 23);
            this.btBuscarUsuarioUsername.TabIndex = 0;
            this.btBuscarUsuarioUsername.Text = "Buscar Usuario (username)";
            this.btBuscarUsuarioUsername.UseVisualStyleBackColor = false;
            this.btBuscarUsuarioUsername.Click += new System.EventHandler(this.btBuscarUsuarioUsername_Click);
            // 
            // btBuscarUsuarioDNI
            // 
            this.btBuscarUsuarioDNI.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.btBuscarUsuarioDNI.BackColor = System.Drawing.Color.AliceBlue;
            this.btBuscarUsuarioDNI.Dock = System.Windows.Forms.DockStyle.Fill;
            this.btBuscarUsuarioDNI.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btBuscarUsuarioDNI.Location = new System.Drawing.Point(0, 0);
            this.btBuscarUsuarioDNI.Name = "btBuscarUsuarioDNI";
            this.btBuscarUsuarioDNI.Size = new System.Drawing.Size(75, 23);
            this.btBuscarUsuarioDNI.TabIndex = 0;
            this.btBuscarUsuarioDNI.Text = "Buscar Usuario (DNI)";
            this.btBuscarUsuarioDNI.UseVisualStyleBackColor = false;
            this.btBuscarUsuarioDNI.Click += new System.EventHandler(this.btBuscarUsuarioDNI_Click);
            // 
            // tbBuscarUsuarioDNI
            // 
            this.tbBuscarUsuarioDNI.Font = new System.Drawing.Font("Bodoni MT", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.tbBuscarUsuarioDNI.Location = new System.Drawing.Point(0, 0);
            this.tbBuscarUsuarioDNI.MaxLength = 8;
            this.tbBuscarUsuarioDNI.Name = "tbBuscarUsuarioDNI";
            this.tbBuscarUsuarioDNI.Size = new System.Drawing.Size(140, 30);
            this.tbBuscarUsuarioDNI.TabIndex = 0;
            // 
            // tbBuscarUsuarioUsername
            // 
            this.tbBuscarUsuarioUsername.Font = new System.Drawing.Font("Bodoni MT", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.tbBuscarUsuarioUsername.Location = new System.Drawing.Point(0, 0);
            this.tbBuscarUsuarioUsername.MaxLength = 50;
            this.tbBuscarUsuarioUsername.Name = "tbBuscarUsuarioUsername";
            this.tbBuscarUsuarioUsername.Size = new System.Drawing.Size(200, 30);
            this.tbBuscarUsuarioUsername.TabIndex = 0;
            // 
            // btGuardarCambios
            // 
            this.btGuardarCambios.BackColor = System.Drawing.Color.AliceBlue;
            this.btGuardarCambios.Font = new System.Drawing.Font("Bodoni MT", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btGuardarCambios.Location = new System.Drawing.Point(0, 0);
            this.btGuardarCambios.Name = "btGuardarCambios";
            this.btGuardarCambios.Size = new System.Drawing.Size(175, 23);
            this.btGuardarCambios.TabIndex = 0;
            this.btGuardarCambios.Text = "Guardar Cambios";
            this.btGuardarCambios.UseVisualStyleBackColor = false;
            this.btGuardarCambios.Click += new System.EventHandler(this.btGuardarCambios_Click);
            ((System.ComponentModel.ISupportInitialize)(this.dgvUsuarios)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion


        private void btGuardarCambios_Click(object sender, EventArgs e)
        {
            try
            {
                if (adapter != null)
                {
                    cmdBuilder = new SqlCommandBuilder(adapter);
                    changes = ds.GetChanges();
                    if (changes != null)
                    {
                        adapter.Update(changes);
                        MessageBox.Show("CAMBIOS GUARDADOS", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    else
                    {
                        MessageBox.Show("NO HAY CAMBIOS EN LA TABLA", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }

                }
            }
            catch (Exception exc)
            {
                MessageBox.Show("ERROR AL GUARDAR LOS DATOS.\nNo se guardaran los datos. \nVerifique celtas modificadas y cantidad de dígitos modificados.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CLogger.Append("[btGuardarCambios_Click] Exception: " + exc, CLogger.ERROR);      //DEBUG
                this.handler.backToPrincipal();
            }
        }

        private void btBuscarUsuarioUsername_Click(object sender, EventArgs e)
        {
            dgvUsuarios.ClearSelection();
            if (!string.IsNullOrWhiteSpace(tbBuscarUsuarioUsername.Text))
            {
                string searchValue = tbBuscarUsuarioUsername.Text;
                int inRowFinded = -1;
                
                try
                {
                    foreach (DataGridViewRow row in dgvUsuarios.Rows)
                    {
                        if (row.Cells[4].Value.ToString().Equals(searchValue))
                        {
                            dgvUsuarios.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                            row.Selected = true;

                            inRowFinded = row.Index;
                            //MessageBox.Show("ENCONTRE: "+inRowFinded, "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            dgvUsuarios.CurrentCell = row.Cells[0];
                            tbBuscarUsuarioUsername.Clear();
                            break;

                        }
                    }
                  
                }
                catch (Exception exc)
                {
                    tbBuscarUsuarioUsername.Clear();
                    //MessageBox.Show(exc.Message); //DEBUG
                    //CLogger.Append("[btBuscarUsuarioUsername_Click] Exception: " + exc, CLogger.ERROR);      //DEBUG
                    MessageBox.Show("NO SE ENCONTRO EL USUARIO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            else
            {
                MessageBox.Show("NO SE INGRESO USER NAME", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }
        }

        private void btBuscarUsuarioDNI_Click(object sender, EventArgs e)
        {
            dgvUsuarios.ClearSelection();
            if (!string.IsNullOrWhiteSpace(tbBuscarUsuarioDNI.Text) && (!(tbBuscarUsuarioDNI.Text.Length < 8)))
            {
                string searchValue = tbBuscarUsuarioDNI.Text;
                int inRowFinded = -1;
                
                try
                {
                    foreach (DataGridViewRow row in dgvUsuarios.Rows)
                    {
                        if (row.Cells[3].Value.ToString().Equals(searchValue))
                        {
                            dgvUsuarios.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                            row.Selected = true;
                            inRowFinded = row.Index;
                            //   MessageBox.Show("ENCONTRE: " + inRowFinded, "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            dgvUsuarios.CurrentCell = row.Cells[0];
                            tbBuscarUsuarioDNI.Clear();

                            break;
                        }
                    }
                    
                }
                catch (Exception exc)
                {
                    tbBuscarUsuarioUsername.Clear();
                    //MessageBox.Show(exc.Message);     //DEBUG
                    //CLogger.Append("[btBuscarUsuarioDNI_Click] Exception: " + exc, CLogger.ERROR);      //DEBUG
                    MessageBox.Show("NO SE ENCONTRO EL USUARIO", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            else
            {
                MessageBox.Show("NO SE INGRESO NINGÚN NUMERO DE DNI \nÓ LA CANTIDAD DE DIGITOS ES INCORRECTA", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }
        }

        private void dgvUsuarios_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            dgvUsuarios.SelectionMode = DataGridViewSelectionMode.CellSelect;
        }

    }
}
